package com.hoow.shakoow.launch

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.google.android.gms.ads.MobileAds
import com.hoow.shakoow.ProjectApplication
import com.hoow.shakoow.ProjectConfig
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqAiBase
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityLaunchBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.utils.UserStateUtil
import com.hoow.shakoow.utils.analytics.util.AdvertIdUtil


/** 启动页 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityLaunchBinding

    //定时器
    private var mHandler: Handler? = null

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.launch.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityLaunchBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onContentViewBinded() {
        try {
            //如果已打开，就退出
            if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
                finish()
                return
            }

            // 获取 appconfig 返回
            mNetworkViewModel.onGetAppConfigLiveData.observe(this) {
                //初始化广告id
                getHandler()?.removeCallbacksAndMessages(null)
                getHandler()?.postDelayed({
                    if (AdvertIdUtil.getAdId().isBlank()) {
                        AdvertIdUtil.setAdId(AdvertIdUtil.getAndroidId())
                    }
                    onHandlerAdvertIdFinish()
                }, 5000L)
                initAdvertId(needUseCallback = true)
            }

            // 登录返回
            mNetworkViewModel.onLoginByAdvertIdLiveData.observe(this) {
                if (it.isSuccess) {
                    //获取用户详情
                    mNetworkViewModel.getUserInfo(ReqAiBase(showLoading = false))
                }
            }

            //获取用户详情回调
            mNetworkViewModel.onGetUserInfoLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        if (result.isHadSettingNickNameAndGender()) {
                            // 去摇一摇
                            startToShakePage()
                        } else {
                            // 去设置昵称性别
                            startToSetNickNamePage()
                        }
                    }
                }
            }

            //初始化版本信息
            //mActivityBinding.textLaunchProductVersion.text = getString(
//                R.string.version_flag,
//                "${ProjectConfig.Version_NAME}(${ProjectConfig.Version})"
//            )

            println("Google Mobile Ads SDK Version: " + MobileAds.getVersion())

            // 加载中动画
            mActivityBinding.aviShakeLoading.show()

            mActivityBinding.textVerson.text =
                getString(R.string.version_flag, ProjectConfig.Version_NAME)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        //移除回调
        getHandler()?.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    override fun onResume() {
        super.onResume()

        // 获取app配置
        mNetworkViewModel.getAppConfig(ReqAiBase(showLoading = false))

        //初始化广告id
//        getHandler()?.removeCallbacksAndMessages(null)
//        getHandler()?.postDelayed({
//            if (AdvertIdUtil.getAdId().isBlank()) {
//                AdvertIdUtil.setAdId(AdvertIdUtil.getAndroidId())
//            }
//            onHandlerAdvertIdFinish()
//        }, 5000L)
//        initAdvertId(needUseCallback = true)
    }

    /** 重启时重新调用 */
    fun onRestarLaunch() {
        // 获取app配置
        mNetworkViewModel.getAppConfig(ReqAiBase(showLoading = false))
    }

    /** 获取广告id后的逻辑 */
    private fun onHandlerAdvertIdFinish() {
        //查询是否需要登录
        if (UserStateUtil.isDidLogin()) {
            //获取用户详情
            mNetworkViewModel.getUserInfo(ReqAiBase(showLoading = false))
        } else {
            //广告id登录
            mNetworkViewModel.loginByAdvertId(ReqAiBase(showLoading = false))
        }

        // 跳转昵称页
        //startToSetNickNamePage()
    }

    /** 初始化广告id */
    private fun initAdvertId(needUseCallback: Boolean = false) {
        //初始化广告id
        AdvertIdUtil.init(ProjectApplication.instance) { _, _ ->
            println("======初始化广告id成功")
            //移除回调
            getHandler()?.removeCallbacksAndMessages(null)

            if (needUseCallback) {
                Handler(Looper.getMainLooper()).postDelayed(
                    {
                        //查询是否需要登录
                        onHandlerAdvertIdFinish()
                    },
                    1000
                )
            }
        }
    }

    /** 获取定时器 */
    private fun getHandler(): Handler? {
        if (mHandler == null) {
            mHandler = Handler(Looper.getMainLooper())
        }
        return mHandler
    }
}